package br.com.opet.DAO;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import br.com.opet.vo.*;

public class VendaDAO {
	public static boolean insert(Venda venda)
	{
		try{
			EntityManager manager = EntityManagerFactory.getInstance();
			manager.getTransaction().begin();
			manager.persist(venda);
			manager.getTransaction().commit();
			return true;			
		}
		catch(Exception e){
			return false;
		}
	}
	
	public static Venda SearchById(int idVenda)
	{
		try
		{
			EntityManager manager = EntityManagerFactory.getInstance();
			Query q = manager.createQuery("from Venda where id = :idP");
			q.setParameter("idP", idVenda);
			List<Venda> vendas = q.getResultList();
			if(!vendas.isEmpty()){
				vendas.get(0).setProdutos(vendas.get(0).getProdutos());
				return vendas.get(0);								
			}
			else
			{
				return null;
			}
		}
		catch(Exception e)
		{
			return null;
		}		
	}
	
	public static List<Venda> listAll()
	{
		try
		{
			EntityManager manager = EntityManagerFactory.getInstance();
			Query q = manager.createQuery("from Venda order by data desc");
			List<Venda> vendas = q.getResultList();
			if(!vendas.isEmpty()){
				return vendas;								
			}
			else
			{
				return null;
			}
		}
		catch(Exception e)
		{
			return null;
		}		
	}
	
	public static List<Venda> listAll(Venda venda)
	{
		try
		{
			EntityManager manager = EntityManagerFactory.getInstance();
			Query q = manager.createQuery("from Venda where cliente_id = :idClienteP order by data desc");
			q.setParameter("idClienteP", venda.getCliente().getId());
			List<Venda> vendas = q.getResultList();
			if(!vendas.isEmpty()){
				return vendas;								
			}
			else
			{
				return null;
			}
		}
		catch(Exception e)
		{
			return null;
		}		
	}
}
